package com.share.chat.service.impl;

import com.share.chat.domain.ResultInfo;
import com.share.chat.domain.User;
import com.share.chat.mapper.UserMapper;
import com.share.chat.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * @author 谢佳豪
 * @data 2021/7/3 - 18:12
 * @description
 */
@Service
public class UserServiceImp implements UserService {

    private UserMapper userMapper;

    @Autowired
    public void setUserMapper(UserMapper userMapper) {
        this.userMapper = userMapper;
    }

    @Override
    public User login(String account, String password){
        //对account进行类型的判断
        //判断是邮箱还是手机号的正则表达式
        String em = "^\\w+([-+.]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        String ph = "^((13[0-9])|(15[^4,\\D])|(17[0-9])|(18[0,5-9]))\\d{8}$";

        Map<String, String> param = new HashMap<>();
        if(account.matches(ph)) {
            param.put("telephone", account);
        }else if(account.matches(em)) {
            param.put("email", account);
        }else {
            param.put("username", account);
        }
        param.put("password", password);

        return userMapper.login(param);
    }



    @Override
    public void updateOnlineState(String username, boolean isOnline) {
        userMapper.updateOnlineState(username, isOnline);
    }

    @Override
    public ResultInfo repeatTelephone(String telephone) {
        if (userMapper.selectTelephone(telephone.strip()) > 0){
            //查询出有重复的手机号
            return ResultInfo.failInfo("有重复的手机号");
        }
        return ResultInfo.successInfo("手机号可用");
    }

    @Override
    public ResultInfo repeatUsername(String username) {
        if (userMapper.selectUsername(username.strip()) > 0){
            return ResultInfo.failInfo("有重复的用户名");
        }
        return ResultInfo.successInfo("用户名可用");
    }

    @Override
    public ResultInfo repeatEmail(String email) {
        if (userMapper.selectEmail(email.strip()) > 0) {
            return ResultInfo.failInfo("有重复的邮箱地址");
        }
        return ResultInfo.successInfo("邮箱可用");
    }


    @Override
    public ResultInfo registration(User user) {

        //初始化头像
        user.setPicture(User.PICTURE_2);

        //使用MD5进行密码加密
//        String md5Password = DigestUtils.md5DigestAsHex(user.getPassword().getBytes());

        //重新设置加密的密码
//        user.setPassword(md5Password);

        //在用户表中添加信息
        userMapper.insertUser(user);

        return ResultInfo.successInfo("注册成功");
    }

}
